package com.jiangli.utils.Sreach;

import org.wltea.analyzer.core.IKSegmenter;
import org.wltea.analyzer.core.Lexeme;

import java.io.StringReader;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 搜索工具类（分词和集合操作）
 */
public class SearchUtils {

    /**
     * IK分词
     */
    public static List<String> ikSegment(String text) {
        if (text == null || text.trim().isEmpty()) {
            return Collections.emptyList();
        }

        List<String> result = new ArrayList<>();
        try (StringReader reader = new StringReader(text.trim())) {
            IKSegmenter segmenter = new IKSegmenter(reader, true); // 智能分词
            Lexeme lexeme;
            while ((lexeme = segmenter.next()) != null) {
                result.add(lexeme.getLexemeText());
            }
        } catch (Exception e) {
            result.add(text); // 分词失败时返回原文本
        }

        return result.stream().distinct().collect(Collectors.toList());
    }

    /**
     * 集合交集
     */
    public static <T> Set<T> intersect(Collection<Set<T>> collections) {
        if (collections.isEmpty()) return new HashSet<>();

        Iterator<Set<T>> iterator = collections.iterator();
        Set<T> result = new HashSet<>(iterator.next());

        while (iterator.hasNext()) {
            result.retainAll(iterator.next());
            if (result.isEmpty()) break;
        }

        return result;
    }

    /**
     * 集合并集
     */
    public static <T> Set<T> union(Collection<Set<T>> collections) {
        Set<T> result = new HashSet<>();
        for (Set<T> set : collections) {
            result.addAll(set);
        }
        return result;
    }
}